<template>
  <a-card>
    <h3>{{ id ? "编辑文章" : "新增文章" }}</h3>

    <a-form-model
      :model="articleInfo"
      ref="articleFormRef"
      :rules="artRulesInfo"
      :hideRequiredMark="true"
    >
      <a-form-model-item label="文章标题" prop="title">
        <a-input style="width: 300px" v-model="articleInfo.title"></a-input>
      </a-form-model-item>
      <a-form-model-item label="文章分类" prop="cid">
        <a-select
          v-model="articleInfo.cid"
          style="width: 200px"
          placeholder="请选择分类"
          @change="cateChange"
        >
          <a-select-option
            v-for="category in categoryList"
            :key="category.id"
            :value="category.id"
            >{{ category.name }}</a-select-option
          >
        </a-select>
      </a-form-model-item>
      <a-form-model-item label="文章描述" prop="desc">
        <a-input type="textarea" v-model="articleInfo.desc"></a-input>
      </a-form-model-item>
      <a-form-model-item label="文章缩略图" prop="img">
        <a-upload
          name="file"
          :multiple="false"
          :action="uploadUrl"
          :headers="headers"
          @change="uploadChange"
          listType="picture"
        >
          <a-button type="upload">点击上传</a-button>
          <br />
          <template v-if="id">
            <img
              :src="articleInfo.img"
              style="width: 120px; height: 100px; margin-top: 5px"
              alt="无"
            />
          </template>
        </a-upload>
      </a-form-model-item>
      <a-form-model-item label="文章内容" prop="content">
        <Editor v-model="articleInfo.content"></Editor>
      </a-form-model-item>
      <a-form-model-item>
        <a-button
          type="danger"
          style="margin-right: 15px"
          @click="Ok(articleInfo.id)"
          >{{ articleInfo.id ? "更新" : "提交" }}</a-button
        >
        <a-button type="primary" style="margin-right: 15px" @click="cancel"
          >取消</a-button
        >
      </a-form-model-item>
    </a-form-model>
  </a-card>
</template>

<script>
import { url } from "../../plugin/http";
import Editor from "../editor/Index.vue";
export default {
  props: ["id"],
  data() {
    return {
      articleInfo: {
        id: 0,
        title: "",
        cid: undefined,
        desc: "",
        content: "",
        img: "",
      },
      categoryList: [],
      uploadUrl: url + "/upload",
      headers: {},
      artRulesInfo: {
        title: [{ required: true, message: "请输入文章标题" }],
        cid: [{ required: true, message: "请选择分类" }],
        img: [{ required: true, message: "请选择文章缩略图" }],
        desc: [
          { required: true, message: "请输入文章描述" },
          { max: 120, message: "描述最多120字", trigger: "change" },
        ],
        content: [{ required: true, message: "请输入文章内容" }],
      },
    };
  },
  created() {
    this.getCategoryList();
    this.headers = {
      Authorization: `Bearer ${window.sessionStorage.getItem("token")}`,
    };
    if (this.id) {
      this.getArticleInfo(this.id);
    }
  },
  methods: {
    // 查询文章信息
    async getArticleInfo(id) {
      if (id > 0) {
        const { data: res } = await this.$http.get(`/article/${id}`);
        if (res.status != 200) return this.$message.error(res.msg);
        this.articleInfo.id = res.data.ID;
        this.articleInfo.title = res.data.title;
        this.articleInfo.cid = res.data.category.id;
        this.articleInfo.desc = res.data.desc;
        this.articleInfo.content = res.data.content;
        this.articleInfo.img = res.data.img;
      }
    },
    // 获取分类
    async getCategoryList() {
      const { data: res } = await this.$http.get("/categories");
      if (res.status != 200) return this.$message.error("获取分类信息失败");
      this.categoryList = res.data;
    },
    // 选择分类
    cateChange(value) {
      this.articleInfo.cid = value;
    },
    // 上传文件
    uploadChange(info) {
      if (info.file.status !== "uploading") {
      }
      if (info.file.status === "done") {
        this.$message.success("图片上传成功");
        const imgUrl = info.file.response.url;
        this.articleInfo.img = imgUrl;
      } else if (info.file.status === "error") {
        this.$message.error("图片上传失败");
      }
    },
    // 提交表单
    Ok(id) {
      this.$refs.articleFormRef.validate(async (valid) => {
        if (id == 0) {
          // 新增文章
          const { data: res } = await this.$http.post(
            "/article/add",
            this.articleInfo
          );
          if (res.status != 200) return this.$message.error("新增文章失败");
          this.$message.success("新增文章成功");
          this.$router.push({ name: "articleList" });
        } else {
          // 更新文章
          const { data: res } = await this.$http.put(
            `/article/${id}`,
            this.articleInfo
          );
          if (res.status != 200) return this.$message.error("更新文章失败");
          this.$message.success("更新文章成功");
          this.$router.push({ name: "articleList" });
        }
      });
    },
    cancel() {
      this.$refs.articleFormRef.resetFields();
    },
  },
  components: {
    Editor,
  },
};
</script>

<style lang="scss" scoped>
</style>